#include "videoselectwidget.h"

VideoSelectWidget::VideoSelectWidget(QWidget *parent) : QWidget(parent)
{

    currentPage = 1; // 初始化当前页码为 1
    itemsPerPage = 10; // 每页显示 10 项
    this->initUI();
    this->resize(600, 600);
}

void VideoSelectWidget::initUI()
{



    this->con=MyControl::getInstance();
    this->title = new QLabel("录像选择界面", this);
    this->text = new QLabel("请输入日期", this);
    this->date_button = new QPushButton("", this);
    //this->calendarWidget=new QCalendarWidget(this);

    this->listWidget = new QListWidget(this); // 列表父为窗口，由布局管理
    this->prePage = new QPushButton("上一页", this);
    this->nextPage = new QPushButton("下一页", this);
    this->ensure = new QPushButton("确定", this);
    this->cancel = new QPushButton("取消", this);

    /******************** 2. 初始化控件属性 ********************/
    date_button->setMinimumSize(150, 40); // 日期按钮尺寸
    listWidget->setMinimumHeight(300);    // 列表最小高度
   // listWidget->addItem("2025-03-10 14:30 执法录像"); // 测试数据

    /******************** 3. 创建布局（子布局无父，主布局父为窗口） ********************/
    this->layout_H1 = new QHBoxLayout();
    this->layout_H2 = new QHBoxLayout();
    this->layout_H3 = new QHBoxLayout();
    this->layout_H4 = new QHBoxLayout();
    this->layout_H5 = new QHBoxLayout();
    this->layout_V = new QVBoxLayout(this);

    /******************** 4. 填充子布局内容 ********************/
    // 标题行
    layout_H1->addWidget(title);
    layout_H1->setAlignment(Qt::AlignCenter);

    // 日期行
    layout_H2->addWidget(text);
    layout_H2->addWidget(date_button);
    layout_H2->setSpacing(20);

    // 列表行
    layout_H3->addWidget(listWidget); // 列表直接添加到水平布局

    // 分页行
    layout_H4->addWidget(prePage);
    layout_H4->addWidget(nextPage);
    layout_H4->setSpacing(20);

    // 按钮行
    layout_H5->addWidget(ensure);
    layout_H5->addWidget(cancel);
    layout_H5->setSpacing(20);


    layout_V->addLayout(layout_H1);
    layout_V->addLayout(layout_H2);
    layout_V->addLayout(layout_H3);
    layout_V->addLayout(layout_H4);
    layout_V->addLayout(layout_H5);
    layout_V->setSpacing(25);       // 垂直间距
    layout_V->setContentsMargins(50, 30, 50, 30); // 四周边距

    calendarWidget = new QCalendarWidget(this);
    calendarWidget->setWindowFlags(Qt::Popup); // 设置为弹出窗口


//    this->listWidget=new QListWidget(this);
    this->listWidget->setViewMode(QListView::IconMode);
    this->listWidget->setFixedSize(800,600);
    listWidget->setMinimumWidth(150);
    listWidget->setFont(QFont("宋体",12));

    listWidget->setIconSize(QSize(200,200));
    QPalette pal=listWidget->palette();
    pal.setColor(QPalette::Base,Qt::transparent);//底色透明
    listWidget->setPalette(pal);
    listWidget->setAutoFillBackground(false);
    listWidget->setStyleSheet("QListWidget{border:none;}");
    listWidget->setDragEnabled(false);//禁止拖拽


//    this->model=this->con->getModel("video_file");
//    QString sql=QString("select *from video_files where user_id=%1 ORDER BY video_files.video_id DESC;").arg(1);
//    this->videos=this->model->getVideoInfo((char *)sql.toStdString().c_str());

//    this->selectvideos=this->videos;
    this->SelectDataBase();


    //如果是全部，第一次就会有滑块，这里为了避免直接加载当前页
    loadPage(currentPage);

    connect(this->date_button,&QPushButton::clicked,this,&VideoSelectWidget::showCalender);
    connect(calendarWidget, &QCalendarWidget::activated, this, &VideoSelectWidget::selectCalender);

    connect(prePage, &QPushButton::clicked, this, &VideoSelectWidget::onPrePageClicked);
    connect(nextPage, &QPushButton::clicked, this, &VideoSelectWidget::onNextPageClicked);

    connect(ensure,&QPushButton::clicked,this,&VideoSelectWidget::onEnsureClicked);
    connect(cancel,&QPushButton::clicked,this,&VideoSelectWidget::onRetClicked);



}

void VideoSelectWidget::loadPage(int page)
{
    listWidget->clear();
    int startIndex=(page-1)*itemsPerPage;
    int endIndex=qMin(startIndex+itemsPerPage,selectvideos.size());

    for(int i=startIndex;i<endIndex;i++)
    {
        Video *video = selectvideos[i];
        QListWidgetItem *item = new QListWidgetItem(QIcon(video->getVideo_img_path()), video->getVideo_name(), listWidget);

        int globalIndex = videos.indexOf(video);
        item->setData(Qt::UserRole, globalIndex);
        listWidget->addItem(item);
    }

    prePage->setEnabled(page>1);//判断按钮是否能用
    nextPage->setEnabled(endIndex<selectvideos.size());
}

void VideoSelectWidget::SelectDataBase()
{
    this->model=this->con->getModel("video_file");
    QString sql=QString("select *from video_files where user_id=%1 ORDER BY video_files.video_id DESC;").arg(id);
    this->videos=this->model->getVideoInfo((char *)sql.toStdString().c_str());

    this->selectvideos=this->videos;
}

void VideoSelectWidget::showEvent(QShowEvent *event)
{
       SelectDataBase();
       loadPage(currentPage);
       QWidget::showEvent(event);
}

void VideoSelectWidget::showCalender()
{
    QPoint pos=date_button->mapToGlobal(QPoint(0,date_button->height()));
    this->calendarWidget->move(pos);
    this->calendarWidget->show();
}

void VideoSelectWidget::selectCalender(const QDate &date)
{
    QString dateStr = date.toString("yyyy-MM-dd");
    date_button->setText(dateStr);
    this->calendarWidget->hide();


    qDebug()<<"dateStr="<<dateStr;

    QList<Video*> filteredVideos;
    for (Video* video : videos)
    {

           QDate videoDate = video->extractDateFromName();
           QString videoDateStr=videoDate.toString("yyyy-MM-dd");
           qDebug()<<"videoDateStr="<<videoDateStr;

           if (videoDateStr == dateStr)
           {

               filteredVideos.push_back(video);
           }
     }


    if (filteredVideos.isEmpty()) {
            QMessageBox::information(this, "提示", "按照该日期查询，未找到相关视频。");
        }

    this->selectvideos=filteredVideos;
    currentPage=1;
    loadPage(currentPage);

}

void VideoSelectWidget::onNextPageClicked()
{
    int totalPages=(videos.size()+itemsPerPage-1)/itemsPerPage;
    if(currentPage<totalPages)
    {
        currentPage++;
        loadPage(currentPage);
    }
}

void VideoSelectWidget::onPrePageClicked()
{
    if(currentPage>1)
    {
        currentPage--;
        loadPage(currentPage);
    }
}

void VideoSelectWidget::onEnsureClicked()
{
    QList<QListWidgetItem *> selectedItems = listWidget->selectedItems();
      if (selectedItems.isEmpty()) {
          QMessageBox::warning(this, "未选择文件", "请先选择一个录像文件");
          return;
      }

      // 2. 处理单个选中项（假设单选）
      QListWidgetItem *item = selectedItems.first();
      QString videoName = item->text(); // 显示文本（如文件名）
      qDebug()<<videoName;
//      QString videoPath = item->data(Qt::UserRole).toString(); // 存储的路径
      int videoIndex = item->data(Qt::UserRole).toInt();
          qDebug() << "选中文件索引：" << videoIndex;


      QString filepath="../video/"+videoName+".H264";
      qDebug() << "选中文件：" << videoName ;



    this->reolay=new VideoReolayWidget(filepath);
    connect(this->reolay,&VideoReolayWidget::ToSelect,this,&VideoSelectWidget::ReolayToSelect);

    this->reolay->setList(videos);
    this->reolay->setVideoIndex(videoIndex);
    this->hide();
    this->reolay->show();
}

void VideoSelectWidget::ReolayToSelect()
{
    this->reolay->hide();
    this->show();
}

void VideoSelectWidget::onRetClicked()
{
    emit SelectToMain();
    qDebug()<<"发送返回信号";
}




